package com.song.ejf.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.opensymphony.xwork2.ActionSupport;
import com.song.ejf.page.Page;
import com.song.ejf.pojo.SUser;
import com.song.ejf.service.RoleService;
import com.song.ejf.service.UserService;
import com.song.ejf.util.DateUtil;
import com.song.ejf.util.JSONUtil;
import com.song.ejf.util.UUIDUtil;

/**
 * @author 作者ryan_song E-mail:song316@gmai.com
 * @version 创建时间：2011-3-3 下午10:12:32 类说明
 */
public class UserAction extends ActionSupport {
	Log log = LogFactory.getLog(UserAction.class);
	private static final long serialVersionUID = -6356307819518359036L;
	private SUser user;
	private Page page;
	private String checkItems;
	private String verifyCode;
	public List<Map<String, String>> allRole;
	public String usersRole;
	@Autowired()
	@Qualifier("userService")
	private UserService userService;
	@Autowired()
	public RoleService roleService;
	
	/**
	 * 准备配置用户角色
	 * @return
	 */
	public String pConfUserRole(){
		try {
			user = userService.findUserById(user.getId());
			//加载所有角色
			allRole = roleService.loadAllRes();
			//加载所选用户的所有角色.
			usersRole = JSONUtil.convertObj2Json(userService.loadRoleByUserId(user.getId()));
		} catch (Exception e) {
			log.error("跳转到配置用户角色页面异常",e);
		}
		return "pConfUserRole";
	}
	
	/**
	 * 配置用户角色
	 * @return
	 */
	public String confUserRole(){
		try {
			if(checkItems == null){
				addActionMessage("配置用户角色失败,选择角色出错.");
				return "confUserRole";
			}
			if(userService.updateUserRole(checkItems.split(","), user.getId())){
				addActionMessage("配置用户角色成功.");
			}else{
				addActionMessage("配置用户角色失败.");
			}
		} catch (Exception e) {
			log.error("配置用户角色异常.",e);
		}
		return "confUserRole";
	}
	/**
	 * 重置密码为12345abc
	 * @return
	 */
	public String resetPassword(){
		try {
			if(StringUtils.isBlank(checkItems)){
				addActionMessage("删除用户失败!");
				return "delUser";
			}
			String [] arr = checkItems.split(",");
			for (int i = 0; i < arr.length; i++) {
				user = userService.findUserById(arr[i]);
				user.setPassword("12345abc");
				userService.saveOrUpdateUser(user);
			}
			addActionMessage("重置" + arr.length + "个用户的密码成功!新密码为:12345abc");
		} catch (Exception e) {
			log.error("重置密码.",e);
		}
		return "resetPassword";
	}
	/**
	 * 准备添加用户
	 * @return
	 */
	public String pAddUser(){
		return "pAddUser";
	}
	/**
	 * 添加用户.
	 * @return
	 */
	public String addUser(){
		try {
			if(user != null){
				user.setLastModifyTime(DateUtil.formatDate());
				user.setId(UUIDUtil.makeUUID());
				user.setPassword("12345abc");
				userService.saveOrUpdateUser(user);
				addActionMessage("添加用户成功!初始密码为:12345abc");
			}else{
				addActionMessage("添加用户失败!");
			}
		} catch (Exception e) {
			log.error("添加用户异常.",e);
		}
		return "addUser";
	}
	/**
	 * 列出所有用户
	 * @return
	 */
	public String listUser(){
		try {
			if(page == null){
				page = new Page();
			}
			if(user == null){
				user = new SUser();
			}
			userService.loadUserPage(page, user.getUsername(),user.getName());
		} catch (Exception e) {
			log.error("用户列表异常.",e);
		}
		return "listUser";
	}
	/**
	 * 删除用户
	 * @return
	 */
	public String delUser(){
		try {
			if(StringUtils.isBlank(checkItems)){
				addActionMessage("删除用户失败!");
				return "delUser";
			}
			boolean flag = userService.delUser(checkItems.split(","));
			if(flag){
				addActionMessage("删除用户成功!");
			}else{
				addActionMessage("删除用户失败!");
			}
		} catch (Exception e) {
			log.error("删除用户异常.",e);
		}
		return "delUser";
	}
	/**
	 * 准备编辑用户
	 * @return
	 */
	public String pEditUser(){
		try {
			user = userService.findUserById(user.getId());
		} catch (Exception e) {
			log.error("跳转到编辑用户页面异常.",e);
		}
		return "pEditUser";
	}
	/**
	 * 编辑用户
	 * @return
	 */
	public String editUser(){
		try {
			if(user != null){
				user.setLastModifyTime(DateUtil.formatDate());
				userService.saveOrUpdateUser(user);
				addActionMessage("修改用户成功!");
			}else{
				addActionMessage("修改用户失败!");
			}
		} catch (Exception e) {
			log.error("编辑用户异常.",e);
		}
		return "editUser";
	}
	/**
	 * 登出
	 */
	public String logout(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.removeAttribute("userId");
		session.removeAttribute("username");
		session.removeAttribute("name");
		session.removeAttribute("access");
		return "login";
	}
	/**
	 * 登录
	 * @return
	 */
	public String login() {
		try {
			if(user == null){
				user = new SUser();
			}
			if(StringUtils.isBlank(user.getUsername())){
				addActionMessage("用户名不能为空!");
				return "login";
			}
			if(StringUtils.isBlank(user.getPassword())){
				addActionMessage("密码不能为空!");
				return "login";
			}
			if(StringUtils.isBlank(verifyCode)){
				addActionMessage("验证码不能为空!");
				return "login";
			}
			String rand = (String)ServletActionContext.getRequest().getSession().getAttribute("verifyCode");
			if(StringUtils.isBlank(rand)){
				addActionMessage("验证码已失效,请刷新后,重新输入!");
				return "login";
			}
			if(!(rand.toLowerCase()).equals(verifyCode.toLowerCase()) ){
				addActionMessage("验证码错误,请刷新后,重新输入!");
				return "login";
			}
			user = userService.getUserByUsernameAndPwd(user.getUsername(), user.getPassword());
			//结果不为空,登录成功.
			if(user != null){
				HttpSession session = ServletActionContext.getRequest().getSession();
				session.setAttribute("userId", user.getId());
				session.setAttribute("username", user.getUsername());
				session.setAttribute("name", user.getName());
				session.setAttribute("access", roleService.loadResByUserId(user.getId()));
				return "loginSuccess";
			}
			addActionMessage("用户名或密码错误!");
		} catch (Exception e) {
			log.error("用户登录异常.",e);
		}
		return "login";
	}
	/**
	 * 验证码
	 * @return
	 */
	public String vCode() {
		// 验证码图片的宽度。
		int width = 70;
		// 验证码图片的高度。
		int height = 30;
		BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffImg.createGraphics();
		// 创建一个随机数生成器类。
		Random random = new Random();
		// 设定图像背景色(因为是做背景，所以偏淡)
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		// 创建字体，字体的大小应该根据图片的高度来定。
		Font font = new Font("Times New Roman", Font.HANGING_BASELINE, 28);
		// 设置字体。
		g.setFont(font);
		// 画边框。
		g.setColor(Color.BLACK);
		g.drawRect(0, 0, width - 1, height - 1);
		// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到。
		// g.setColor(Color.GRAY);
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		// randomCode用于保存随机产生的验证码，以便用户登录后进行验证。
		StringBuffer randomCode = new StringBuffer();
		// 设置默认生成4个验证码
		int length = 4;
		// 设置备选验证码:包括"a-z"和数字"0-9"
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		int size = base.length();
		// 随机产生4位数字的验证码。
		for (int i = 0; i < length; i++) {
			// 得到随机产生的验证码数字。
			int start = random.nextInt(size);
			String strRand = base.substring(start, start + 1);
			// 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(strRand, 15 * i + 6, 24);
			// 将产生的四个随机数组合在一起。
			randomCode.append(strRand);
		}
		// 将四位数字的验证码保存到Session中。
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		session.setAttribute("verifyCode", randomCode.toString());
		// 图象生效
		g.dispose();
		// 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 将图像输出到Servlet输出流中。
		try {
			ServletOutputStream sos = response.getOutputStream();
			ImageIO.write(buffImg, "jpeg", sos);
			sos.flush();
			sos.close();
		} catch (IOException e) {
			log.error("<<<<<<<<<生成验证码失败!!!",e);
		}
		return null;
	}

	Color getRandColor(int fc, int bc) {
		// 给定范围获得随机颜色
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	//////////////////////////////////////////////////////////////

	public String getVerifyCode() {
		return verifyCode;
	}

	public SUser getUser() {
		return user;
	}

	public void setUser(SUser user) {
		this.user = user;
	}

	public void setVerifyCode(String verifyCode) {
		this.verifyCode = verifyCode;
	}
	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
	public String getCheckItems() {
		return checkItems;
	}
	public void setCheckItems(String checkItems) {
		this.checkItems = checkItems;
	}

	public List<Map<String, String>> getAllRole() {
		return allRole;
	}

	public void setAllRole(List<Map<String, String>> allRole) {
		this.allRole = allRole;
	}

	public String getUsersRole() {
		return usersRole;
	}

	public void setUsersRole(String usersRole) {
		this.usersRole = usersRole;
	}
}
